import json
import requests
from py3db.mysql import MySql
from config.db import DB_CONFIG


class Translate:
    def __init__(self):
        self.result = None
        self.url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'

    @classmethod
    def create_db_connect(cls):
        return MySql(
            ip=DB_CONFIG['host'],
            user_name=DB_CONFIG['user'],
            password=DB_CONFIG['password'],
            database="crawler",
            table="crawler_translate"
        )

    def search_translate_from_db(self, chinese_key):
        db = self.create_db_connect()
        result = db.select("crawler_translate", condition_dict={'chinese_key': chinese_key})
        db.close_connect()
        return result

    def add_translate(self, chinese_key, english_key):
        db = self.create_db_connect()
        db.insert_one("crawler_translate", [None, chinese_key, english_key, None, None])
        db.close_connect()

    # 翻译函数，word 需要翻译的内容
    def translate(self, word):
        # 传输的参数，其中 i 为需要翻译的内容
        key = {
            'type': "AUTO",
            'i': word,
            "doctype": "json",
            "version": "4.1",
            "keyfrom": "fanyi.web",
            "ue": "UTF-8",
            "action": "FY_BY_CLICKBUTTON",
            "typoResult": "true"
        }
        # key 这个字典为发送给有道词典服务器的内容
        response = requests.post(self.url, data=key)
        # 判断服务器是否相应成功
        if response.status_code == 200:
            # 然后相应的结果
            return response.text
        else:
            print("有道词典调用失败")
            # 相应失败就返回空
            return None

    def chinese_to_english(self, repsonse):
        # 通过 json.loads 把返回的结果加载成 json 格式
        delete_list = ("the", "of", "a", "an", "to")
        result = json.loads(repsonse)['translateResult']
        result = result[0][0]['tgt'].lower()
        result = list(filter(lambda item: item not in delete_list, result.split()))
        if result[0] == "name":
            result = result[::-1]
        self.result = "_".join(result).replace(",", "").replace(":", "")

    def get_english_word(self, chinese_word=str()):
        search_result = self.search_translate_from_db(chinese_word)
        if len(search_result):
            self.result = search_result[0][2]
        else:
            list_trans = self.translate(chinese_word)
            self.chinese_to_english(list_trans)
            self.add_translate(chinese_word, self.result)
        return self


if __name__ == '__main__':
    translate = Translate()
    print(translate.get_english_word("花园").result)
